package main

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"log"
	"net/http"
	"strings"
)

// Method Override 中间件检查从请求中重写的方法，并使用它来代替原来的方法。todo...
//
// 出于安全原因，只有 POST 方法可以被重写。
func main() {
	e := echo.New()
	e.Pre(middleware.MethodOverrideWithConfig(middleware.MethodOverrideConfig{
		Getter: middleware.MethodFromForm("String"),
	}))

	e.POST("/user", GetUserInfo)

	e.Start(":80")

}

func CustomLoggerConfig() middleware.LoggerConfig {
	l := middleware.LoggerConfig{
		Skipper: func(c echo.Context) bool {
			uri := c.Request().RequestURI
			if strings.Contains(uri, "/index") {
				log.Println("uri:", uri, "--->>>Skipper-true")
				return true
			}
			log.Println("uri:", uri, "--->>>Skipper-false")
			return false
		},
		Format: "method=${method}, uri=${uri}, status=${status}\n",
	}
	return l
}

func GetUserInfo(c echo.Context) error {
	user := &User{}
	err := c.Bind(user)
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, user)
}

type User struct {
	UserId   int    `json:"userid" form:"userid"`
	UserName string `json:"username" form:"username"`
	Password string `json:"password" form:"password"`
	Email    string `json:"email" form:"email"`
}

func (u *User) String() string {
	return "UserId:" + string(rune(u.UserId)) + " UserName:" + u.UserName + " Password:" + u.Password + " Email:" + u.Email
}
